require "project_id/version"
require 'optparse'
require 'digest'

module ProjectId
	def self.run!(argv)
		argv << '-h' if argv.empty?

		options = {}
		opt_parser =OptionParser.new do |opts|
			opts.banner = "Usage: project_id [options]"

			options[:key] = nil
			opts.on("-k", "--key [JIRA KEY]", String, "Project key in Jira") do |k|
				if k.nil?
					puts opt_parser
				else
					options[:key] = k
				end
			end

			opts.on("-h", "--help", "Show help") do |h|
				options[:help] = h
				puts opt_parser
				exit
			end

			opts.on("-v", "--version", "Show version") do |v|
				options[:version] = v
				puts ProjectId::VERSION
				exit
			end
		end

		begin
			opt_parser.parse!(argv)

			if (options[:key])
				begin
					pkey = options[:key]
					digest = Digest::SHA256.new

					num = digest.hexdigest(pkey).hex % (10 ** 5)
					new_id = num.abs

					puts "#{pkey} => #{new_id}"

				rescue
					puts "[Error] Unable to generate project id"
					exit 1
				end
			end
		rescue OptionParser::InvalidOption, OptionParser::MissingArgument
			puts $!.to_s
			puts opt_parser
			exit
		end
	end
end

